// app/chat.tsx
'use client';

import { useChat } from '@ai-sdk/react';
import { useRef, useEffect } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Card, CardHeader } from "@/components/ui/card";
import ThemeModeButton from '@/components/ThemeModeButton';
import { ChatMessage } from '@/components/ChatMessage';
import MultiModalTextArea from '@/components/MultiModalTextarea';
import { useScrollToBottom } from '@/components/use-scroll-bottom';

// interface Message {
//   id: string;
//   content: string;
//   timestamp: string;
//   isUser: boolean;
// }

export default function ChatInterface() {
  
  const [messageContainerRef, messagesEndRef] = useScrollToBottom<HTMLDivElement>();
  // const scrollToBottom = () => {
  //   if (messageRef.current) {
  //     messageRef.current.scrollTop = messageRef.current.scrollHeight;
  //   }
  // };
  // const scrollToBottom = () => {
  //   messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  // };
  // handleInputChange, append,
  const { messages, input, setInput,  handleSubmit, status, stop } = useChat({});

  // useEffect(() => {
  //   scrollToBottom();
  // }, [messages]);

  const handleSend = () => {
    handleSubmit();
  }
  //   if (inputMessage.trim()) {
  //     const newMessage: Message = {
  //       id: Date.now().toString(),
  //       content: inputMessage,
  //       timestamp: new Date().toLocaleTimeString([], { 
  //         hour: '2-digit', 
  //         minute: '2-digit' 
  //       }),
  //       isUser: true,
  //     };
      
  //     // setMessages([...messages, newMessage]);
  //     setInputMessage("");
  //   }
  // };
  const handleKeyDown = (event: KeyboardEvent) => {
    // console.log('Enter Sending message:');
    if (event.key === 'Enter'){ 
      event.preventDefault(); // 阻止默认的换行行为
      handleSubmit()
    }
  }

  
  return (
    <Card className="flex flex-col h-full mx-auto">
      {/* <CardHeader title="Chat"><ThemeModeButton /></CardHeader> */}
      <div className="flex flex-col min-w-0 gap-6 flex-1 overflow-y-scroll pt-4" ref={messageContainerRef}>
          {messages.map((message) => (
            <div
              key={message.id}
              className={`flex ${message.role === 'user' ? "justify-end" : "justify-start"} gap-4`}
            >
              <ChatMessage id={message.id} 
                  content={message.content} 
                  role={message.role} 
                  timestamp={message.createdAt? message.createdAt:new Date()} 
                  copyVisible={true}
                  actionsVisible={true}></ChatMessage>
            </div>
          ))}
          <div ref={messagesEndRef} className='mb-1'></div>        
      </div>

      <div className='mb-1'>
            {(status === 'submitted' || status === 'streaming') && (
            <div className="flex justify-center gap-2">
              {status === 'submitted'}
              <Button type="button" onClick={() => stop()}>
                Stop
              </Button>
            </div>
          )}
      </div>

      <div className="border-t p-4">
        <div className="flex gap-2">
          <MultiModalTextArea value={input}
            onChange={value => setInput(value)}
            onKeyDown={(e) => handleKeyDown(e)}
            handleSubmit={()=>handleSend()} status={status}            />
        </div>
      </div>
    </Card>
  );
}
